package protomysql

const (
	LengthSize = 3
	NumberSize = 1
)

type MysqlPackage struct {
	data          []byte
	dataLen       int
	PackageLength int
	Number        int
	Payload       []byte
	IsFull        bool
	point         int // 读取body指针
	PayloadStream *MysqlStream
	ResponseCode  int
}

func NewMysqlPackage(data []byte) *MysqlPackage {
	if data == nil {
		return nil
	}

	p := &MysqlPackage{
		data:    data,
		dataLen: len(data),
		IsFull:  true,
		point:   0,
	}
	return p
}

func (p *MysqlPackage) Init() *MysqlPackage {
	if p.point >= p.dataLen {
		return nil
	}

	mysqlStream := NewMysqlStream(p.data)
	p.PackageLength = mysqlStream.ReadFixedLengthInteger(LengthSize)
	p.Number = mysqlStream.ReadFixedLengthInteger(NumberSize)
	if len(p.data) < p.PackageLength+LengthSize+NumberSize {
		// 包不完整
		p.IsFull = false
		return p
	}

	p.IsFull = true
	p.Payload = mysqlStream.ReadBytes(p.PackageLength)
	p.PayloadStream = NewMysqlStream(p.Payload)
	p.point = LengthSize + NumberSize + p.PackageLength
	p.data = p.data[p.point:]
	return p
}

func (p *MysqlPackage) InitServer() *MysqlPackage {
	mysqlStream := NewMysqlStream(p.data)
	p.PackageLength = mysqlStream.ReadFixedLengthInteger(3)
	p.Number = mysqlStream.ReadFixedLengthInteger(1)
	if len(p.data) < p.PackageLength+LengthSize+NumberSize {
		// 包不完整
		p.IsFull = false
		return p
	}

	p.ResponseCode = mysqlStream.ReadFixedLengthInteger(1)
	p.Payload = mysqlStream.ReadBytes(p.PackageLength)
	p.PayloadStream = NewMysqlStream(p.Payload)
	return p
}

func (p *MysqlPackage) AppendData(data []byte) {
	p.data = append(p.data, data...)
}
